package ru.stepuk.modern;

import ru.stepuk.modern.events.Event;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 *
 * @author ivan
 */
public class Timeline {

    private static final int RATE = 1000;
    private TreeMap<Long, Event> schedule = new TreeMap<Long, Event>();
    private boolean stopped = false;
    private double now = 0;

    public void play() {

        stopped = false;
        while (!schedule.isEmpty() && !stopped) {
            Entry<Long, Event> next = schedule.firstEntry();
            now = toRealTime(next.getKey());
            next.getValue().process();
            schedule.remove(next.getKey());
        }
    }

    public void stop() {
        now = 0;
        stopped = true;
        clear();
    }

    public long addEvent(double time, Event event) {
        long mt = toModelTime(time);
        while (schedule.containsKey(mt)) {
            mt++;
        }
        schedule.put(mt, event);
        return mt;
    }

    public void deleteEvent(double time) {
        schedule.remove(toModelTime(time));
    }

    public void deleteEvent(long time) {
        schedule.remove(time);
    }

    public void clear() {

        schedule.clear();
    }

    public double now() {
        return now;
    }

    private long toModelTime(double realTime) {
        return (long) (realTime * RATE);
    }

    public double toRealTime(long modelTime) {
        return ((double) modelTime) / RATE;
    }
}
